//
//  ZJDynamicSectonView.m
//  LovingPartyBuilding
//
//  Created by ZJ on 2017/6/6.
//  Copyright © 2017年 刘应平. All rights reserved.
//

#import "ZJDynamicSectonView.h"
#import "ZJDyamicImageView.h"
#import "STPhotoBroswer.h"
@interface ZJDynamicSectonView ()
/** 头像 */
@property (nonatomic, strong) UIImageView *headerImageView;
/** 名字 */
@property (nonatomic, strong) UILabel *name;
/** 文字内容 */
@property (nonatomic, strong) UILabel *textContentLabel;
/** 时间 */
@property (nonatomic, strong) UILabel *time;
/** 删除按钮 */
@property (nonatomic, strong) UIButton *delect;
/** 点赞 */
@property (nonatomic, strong) UIButton *like;
/** 评论按钮 */
@property (nonatomic, strong) UIButton *comment;
/** 下划线 */
@property (nonatomic, strong) UILabel *underLine;

@end

@implementation ZJDynamicSectonView

- (instancetype)initWithReuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithReuseIdentifier:reuseIdentifier];
    if (self) {
        self.contentView.backgroundColor = [UIColor whiteColor];
        [self.contentView addSubview:self.headerImageView];
        [self.contentView addSubview:self.name];
        [self.contentView addSubview:self.textContentLabel];
        [self.contentView addSubview:self.time];
        [self.contentView addSubview:self.delect];
        [self.contentView addSubview:self.like];
        [self.contentView addSubview:self.comment];
        [self.contentView addSubview:self.underLine];
        
        self.headerImageView.sd_layout
        .topSpaceToView(self.contentView, 12 * [UIScreen zj_screenHScale])
        .leftSpaceToView(self.contentView, 12 * [UIScreen zj_screenWScale])
        .widthIs(40 * [UIScreen zj_screenWScale])
        .heightEqualToWidth();
        
        self.headerImageView.sd_cornerRadius = @(20 * [UIScreen zj_screenWScale]);
        
        
        self.name.sd_layout
        .topSpaceToView(self.contentView, 15 * [UIScreen zj_screenHScale])
        .leftSpaceToView(self.headerImageView, 10 * [UIScreen zj_screenWScale])
        .rightSpaceToView(self.contentView,12 * [UIScreen zj_screenWScale])
        .heightIs([NSString heightWithTextFont:self.name.font]);
        
        self.textContentLabel.sd_layout
        .topSpaceToView(self.name, 5 * [UIScreen zj_screenHScale])
        .leftEqualToView(self.name)
        .widthIs([UIScreen zj_screenWith] - (12 * 2 + 40 + 10) * [UIScreen zj_screenWScale])
        .heightIs(100);
        
        
        self.underLine.sd_layout
        .leftSpaceToView(self.contentView, 10 * [UIScreen zj_screenWScale])
        .rightSpaceToView(self.contentView, 10 * [UIScreen zj_screenWScale])
        .bottomSpaceToView(self.contentView, 0)
        .heightIs(1);
        
        self.comment.sd_layout
        .bottomSpaceToView(self.contentView, 8 * [UIScreen zj_screenHScale])
        .rightSpaceToView(self.contentView, 21 * [UIScreen zj_screenWScale])
        .widthIs(58 * [UIScreen zj_screenWScale])
        .heightIs(20 * [UIScreen zj_screenHScale]);
        
        self.like.sd_layout
        .bottomEqualToView(self.comment)
        .rightSpaceToView(self.comment, 0)
        .widthRatioToView(self.comment, 1)
        .heightRatioToView(self.comment, 1);
        
        self.time.sd_layout
        .topEqualToView(self.comment)
        .leftEqualToView(self.name)
        .widthIs(100)
        .heightRatioToView(self.comment, 1);
        
        self.delect.sd_layout
        .topEqualToView(self.time)
        .leftSpaceToView(self.time, 0)
        .heightRatioToView(self.time, 1)
        .widthRatioToView(self.like, 1);
        
        
    }
    return self;
}



#pragma mark - 点击事件
- (void)action_delect:(UIButton *)sender{
    __weak typeof(self) weakSelf = self;
    [self deleteTalkSuccess:^{
        if ([weakSelf.delegate respondsToSelector:@selector(ZJDynamicSectonViewDelegate_DeleteSuccess_index:)]) {
            [weakSelf.delegate ZJDynamicSectonViewDelegate_DeleteSuccess_index:weakSelf.section];
        }
 
    }];
}

- (void)action_like:(UIButton *)sender{
    __weak typeof(self) weakSelf = self;
    if (sender.selected) {//取消点赞
        [self unLikeDyamicSuccess:^{
            sender.selected = NO;
            if ([weakSelf.delegate respondsToSelector:@selector(ZJDynamicSectonViewDelegate_operationSuccess_index:)]) {
                [weakSelf.delegate ZJDynamicSectonViewDelegate_operationSuccess_index:weakSelf.section];
            }
        }];
    }else{//点赞
        [self addLikeDyamicSuccess:^{
            sender.selected = YES;
            if ([weakSelf.delegate respondsToSelector:@selector(ZJDynamicSectonViewDelegate_operationSuccess_index:)]) {
                [weakSelf.delegate ZJDynamicSectonViewDelegate_operationSuccess_index:weakSelf.section];
            }
        }];
    }
}

- (void)action_comment:(UIButton *)sender{
    if ([self.delegate respondsToSelector:@selector(ZJDynamicSectonViewDelegate_commentClick_index:)]) {
        [self.delegate ZJDynamicSectonViewDelegate_commentClick_index:self.section];
    }
    
}

#pragma mark - 网络请求
//点赞
- (void)addLikeDyamicSuccess:(void(^)())success{

    NSDictionary *dict = @{@"ID":self.model.ID,
                           @"CHAT_ID":self.model.PID,
                           @"USERID":[ZJUserInfoModel sharedUserInfo].ORG_ACCOUNT.ID};
    [NetWorkingManager postWithUrlString:[NetWorkingURL addActPraise] Parameter:dict Success:^(id object) {
        NetWorkModel *model = [NetWorkModel yy_modelWithJSON:object];
        if ([model.STATE isEqualToString:@"20000"]) {
            success();
        }
    } Fail:^(id object) {
        
    }];
    
}
//取消点赞
- (void)unLikeDyamicSuccess:(void(^)())success{
    NSDictionary *dict = @{@"CHAT_ID":self.model.PID,
                           @"USERID":[ZJUserInfoModel sharedUserInfo].ORG_ACCOUNT.ID};
    [NetWorkingManager postWithUrlString:[NetWorkingURL delActPraise] Parameter:dict Success:^(id object) {
        NetWorkModel *model = [NetWorkModel yy_modelWithJSON:object];
        if ([model.STATE isEqualToString:@"20000"]) {
            success();
        }
    } Fail:^(id object) {
        
    }];
}

//删除说说
- (void)deleteTalkSuccess:(void(^)())success{
    NSDictionary *dict = @{@"CHAT_ID":self.model.PID,};
    [NetWorkingManager postWithUrlString:[NetWorkingURL delActChat] Parameter:dict Success:^(id object) {
        NetWorkModel *model = [NetWorkModel yy_modelWithJSON:object];
        if ([model.STATE isEqualToString:@"20000"]) {
            success();
        }
    } Fail:^(id object) {
        
    }];

}

#pragma mark - Setter
- (void)setModel:(ZJTalkModel *)model{
    _model = model;
    for (id view in self.contentView.subviews) {
        if ([view isKindOfClass:[ZJDyamicImageView class]]) {
            [view removeFromSuperview];
        }
    }
    //判断是不是自己发表的  只能删除自己发表的
    if ([model.USERID isEqualToString:[ZJUserInfoModel sharedUserInfo].ORG_ACCOUNT.ID]) {
        self.delect.hidden = NO;
    }else{
        self.delect.hidden = YES;
    }
    
    self.like.selected = [self isLike_model:model];
    
    [self.headerImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",BASEIMAGEURL,model.HEADIMAGEURL]] placeholderImage:PlaceholderImage];
    self.name.text = model.UNAME;
    
    if (model.COMMENTLIST || model.PARISELIST) {//点赞信息、评论信息  存在
        self.underLine.hidden = YES;
    }else{
        self.underLine.hidden = NO;
    }
    
    self.textContentLabel.text = model.CONTENT;
    
    self.textContentLabel.sd_layout
    .topSpaceToView(self.name, 7 * [UIScreen zj_screenHScale])
    .leftEqualToView(self.name)
    .widthIs([UIScreen zj_screenWith] - (12 * 2 + 40 + 10) * [UIScreen zj_screenWScale])
    .heightIs([self.textContentLabel getLableSizeWithMaxWidth:self.textContentLabel.width].height);
    [self.textContentLabel updateLayout];
    
    self.time.text = model.CREATEYMD;
    CGSize timeSize = [self.time getLableSizeWithMaxWidth:[UIScreen zj_screenWith]];
    self.time.sd_layout
    .topEqualToView(self.comment)
    .leftEqualToView(self.name)
    .widthIs(timeSize.width)
    .heightRatioToView(self.comment, 1);
    [self.time updateLayout];
    
    //有图片数组
    if (model.IMGLIST_MODEL.count == 1) {
        ZJImageList *imageModel = model.IMGLIST_MODEL[0];
        ZJDyamicImageView *imageView = [ZJDyamicImageView new];
        imageView.contentMode = UIViewContentModeScaleAspectFill;
        imageView.clipsToBounds = YES;
        [imageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",BASEIMAGEURL,imageModel.IMGURL]] placeholderImage:PlaceholderImage];
        imageView.contentMode = UIViewContentModeScaleAspectFill;
        imageView.clipsToBounds = YES;
        [self.contentView addSubview:imageView];
        imageView.tag = 0;
        imageView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapImage:)];
        [imageView addGestureRecognizer:tap];
        imageView.sd_layout
        .leftEqualToView(self.textContentLabel)
        .topSpaceToView(self.contentView, self.textContentLabel.bottom + 8 * [UIScreen zj_screenHScale])
        .widthIs(self.textContentLabel.width / 2)
        .heightEqualToWidth();
        
    }else if (model.IMGLIST_MODEL.count == 2) {
        
        [self imageViewUpdateUI_Model:model showNumber:2];
        
    }else if (model.IMGLIST_MODEL.count >= 3) {
        [self imageViewUpdateUI_Model:model showNumber:3];
    }
}


/**
 imageView 布局 
 showNumber: 一排显示几个
 */
- (void)imageViewUpdateUI_Model:(ZJTalkModel *)model showNumber:(NSInteger)showNumber{
    ///图片间距
    CGFloat imageSpace = 8 * [UIScreen zj_screenWScale];
    //图片的顶部
    CGFloat imageMaxTop = self.textContentLabel.bottom + imageSpace;
    //图片的左部
    CGFloat imageMaxleft = 62 * [UIScreen zj_screenWScale];
    
    ///图片宽度与高度
    CGFloat imageWidth = ([UIScreen zj_screenWith] - (12 * 2 + 40 + 10 + 40) * [UIScreen zj_screenWScale] - imageSpace) / showNumber;
    
    for (int i = 0; i < model.IMGLIST_MODEL.count ; i ++) {
        ZJImageList *imageModel = model.IMGLIST_MODEL[i];
        ZJDyamicImageView *imageView = [ZJDyamicImageView new];
        imageView.contentMode = UIViewContentModeScaleAspectFill;
        imageView.clipsToBounds = YES;
        [imageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",BASEIMAGEURL,imageModel.IMGURL]] placeholderImage:PlaceholderImage];
        [self.contentView addSubview:imageView];
        imageView.tag = i;
        imageView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapImage:)];
        [imageView addGestureRecognizer:tap];
        imageView.sd_layout
        .leftSpaceToView(self.contentView, imageMaxleft + (i % showNumber) *(imageSpace + imageWidth))
        .topSpaceToView(self.contentView, imageMaxTop + (i / showNumber) *(imageSpace + imageWidth))
        .widthIs(imageWidth)
        .heightEqualToWidth();
        
    }
}



//判断点赞数组中有没有当前用户
- (BOOL)isLike_model:(ZJTalkModel *)model{

    NSInteger flag = 0;
    for (int i = 0; i < model.PARISELIST_MODEL.count; i ++) {
        ZJLikeList *likeModel = model.PARISELIST_MODEL[i];
        if ([likeModel.USERID isEqualToString:[ZJUserInfoModel sharedUserInfo].ORG_ACCOUNT.ID]) {
            flag = 1;
        }
    }
    if (flag == 1) {//已经点赞
        return YES;
    }else{
        return NO;
    }
}

- (void)tapImage:(UITapGestureRecognizer *)tap{
    __block NSMutableArray *imageNames = [NSMutableArray array];
    [self.model.IMGLIST_MODEL enumerateObjectsUsingBlock:^(ZJImageList *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [imageNames addObject:obj.IMGURL];
    }];
    STPhotoBroswer *brower = [[STPhotoBroswer alloc] initWithFrame:CGRectMake(0, 0, [UIScreen zj_screenWith], [UIScreen zj_screenHeight]) ImageArray:imageNames currentIndex:tap.view.tag];
    [brower show];

}

#pragma mark - Getters
- (UIImageView *)headerImageView{
    if (_headerImageView == nil){
        _headerImageView = [UIImageView new];
        _headerImageView.contentMode = UIViewContentModeScaleToFill;
    }
    return _headerImageView;
}

- (UILabel *)textContentLabel{
    if (_textContentLabel == nil){
        _textContentLabel = [UILabel new];
        _textContentLabel.font = [UIFont titleTextFont];
        _textContentLabel.textColor = [UIColor textBlackColor];
        _textContentLabel.numberOfLines = 0;
        _textContentLabel.lineSpace = 4 * [UIScreen zj_screenHScale];
        _textContentLabel.characterSpace = 1;
    }
    return _textContentLabel;
}

- (UILabel *)name{
    if (_name == nil){
        _name = [UILabel new];
        _name.font = [UIFont titleTextFont];
        _name.textColor = [UIColor zj_colorWithHexString:@"646a8c"];
    }
    return _name;
}
- (UILabel *)time{
    if (_time == nil){
        _time = [UILabel new];
        _time.font = [UIFont titleTextFont];
        _time.textColor = [UIColor textGrayColor];
    }
    return _time;
}
- (UIButton *)delect{
    if (_delect == nil){
        _delect = [UIButton new];
        [_delect setTitle:@"删除" forState:UIControlStateNormal];
        [_delect setTitleColor:[UIColor zj_colorWithHexString:@"646a8c"] forState:UIControlStateNormal];
        _delect.titleLabel.font = [UIFont subTitleTextFont];
        [_delect addTarget:self action:@selector(action_delect:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _delect;
}
- (UIButton *)like{
    if (_like == nil){
        _like = [UIButton new];
        [_like setTitle:@"点赞" forState:UIControlStateNormal];
        [_like setTitle:@"取消" forState:UIControlStateSelected];
        [_like setTitleColor:[UIColor zj_colorWithHexString:@"646a8c"] forState:UIControlStateNormal];
        _like.titleLabel.font = [UIFont subTitleTextFont];
        [_like setImage:[UIImage imageNamed:@"icon_zan"] forState:UIControlStateNormal];
        [_like setImage:[UIImage imageNamed:@"icon_zan_cancel"] forState:UIControlStateSelected];
        [_like addTarget:self action:@selector(action_like:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _like;
}

- (UIButton *)comment{
    if (_comment == nil){
        _comment = [UIButton new];
        [_comment setTitle:@"评论" forState:UIControlStateNormal];
        _comment.titleLabel.font = [UIFont subTitleTextFont];
        [_comment setImage:[UIImage imageNamed:@"icon_com"] forState:UIControlStateNormal];
        [_comment setTitleColor:[UIColor zj_colorWithHexString:@"646a8c"] forState:UIControlStateNormal];
        [_comment addTarget:self action:@selector(action_comment:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _comment;
}

- (UILabel *)underLine{
    if (_underLine == nil){
        _underLine = [UILabel new];
        _underLine.backgroundColor = [UIColor zj_colorWithHexString:@"ececec"];
    }
    return _underLine;
}

@end
